<template>
  <div class="hot-posts">
    <div class="hot-posts-header">
      <h2>🔥 热门帖子</h2>
      <el-button type="text" @click="refreshHotPosts">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <div class="hot-posts-content">
      <!-- 农夫热门帖子 -->
      <div class="hot-section" v-if="farmerHotPosts.length > 0">
        <div class="section-header">
          <el-tag type="success" size="large" class="section-tag">
            <el-icon><User /></el-icon>
            农夫热门
          </el-tag>
          <span class="section-count">{{ farmerHotPosts.length }} 条</span>
        </div>
        
        <div class="hot-list">
          <div
            v-for="(post, index) in farmerHotPosts"
            :key="post.id"
            class="hot-item"
            :class="{ 'top-three': index < 3 }"
            @click="viewPostDetail(post)"
          >
            <div class="hot-rank">
              <span class="rank-number" :class="getRankClass(index)">{{ index + 1 }}</span>
            </div>
            <div class="hot-content">
              <p class="post-text">{{ post.content }}</p>
              <div class="post-stats">
                <span class="stat-item">
                  <el-icon><Star /></el-icon>
                  {{ post.likes }}
                </span>
                <span class="stat-item">
                  <el-icon><ChatDotRound /></el-icon>
                  {{ post.comments?.length || 0 }}
                </span>
                <span class="hot-score">热度: {{ post.hotScore }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 买家热门帖子 -->
      <div class="hot-section" v-if="buyerHotPosts.length > 0">
        <div class="section-header">
          <el-tag type="primary" size="large" class="section-tag">
            <el-icon><ShoppingBag /></el-icon>
            买家热门
          </el-tag>
          <span class="section-count">{{ buyerHotPosts.length }} 条</span>
        </div>
        
        <div class="hot-list">
          <div
            v-for="(post, index) in buyerHotPosts"
            :key="post.id"
            class="hot-item"
            :class="{ 'top-three': index < 3 }"
            @click="viewPostDetail(post)"
          >
            <div class="hot-rank">
              <span class="rank-number" :class="getRankClass(index)">{{ index + 1 }}</span>
            </div>
            <div class="hot-content">
              <p class="post-text">{{ post.content }}</p>
              <div class="post-stats">
                <span class="stat-item">
                  <el-icon><Star /></el-icon>
                  {{ post.likes }}
                </span>
                <span class="stat-item">
                  <el-icon><ChatDotRound /></el-icon>
                  {{ post.comments?.length || 0 }}
                </span>
                <span class="hot-score">热度: {{ post.hotScore }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="farmerHotPosts.length === 0 && buyerHotPosts.length === 0" class="empty-state">
        <el-empty description="暂无热门帖子" />
      </div>
    </div>

    <!-- 帖子详情对话框 -->
    <el-dialog
      v-model="showPostDetail"
      :title="selectedPost ? `${selectedPost.author.name} 的帖子` : '帖子详情'"
      width="800px"
      align-center
      destroy-on-close
    >
      <PostDetail
        v-if="selectedPost"
        :post="selectedPost"
        :current-user="currentUser"
        @close="showPostDetail = false"
        @like="handleLike"
        @dislike="handleDislike"
        @add-comment="handleAddComment"
        @add-reply="handleAddReply"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import PostDetail from './PostDetail.vue'

const props = defineProps({
  // 所有帖子数据
  posts: {
    type: Array,
    default: () => []
  },
  // 当前用户信息
  currentUser: {
    type: Object,
    required: true
  }
})

const emit = defineEmits([
  'like',
  'dislike',
  'add-comment',
  'add-reply'
])

// 响应式数据
const showPostDetail = ref(false)
const selectedPost = ref(null)
const loading = ref(false)

//前端测试
// 修改计算属性以使用示例数据
const effectivePosts = computed(() => {
  return props.posts.length > 0 ? props.posts : samplePosts
})

// 更新 farmerHotPosts 和 buyerHotPosts 计算属性
const farmerHotPosts = computed(() => {
  const farmerPosts = effectivePosts.value.filter(post => post.author?.type === 'farmer')
  return calculateHotPosts(farmerPosts).slice(0, 10)
})

const buyerHotPosts = computed(() => {
  const buyerPosts = effectivePosts.value.filter(post => post.author?.type === 'buyer')
  return calculateHotPosts(buyerPosts).slice(0, 10)
})

// 计算热门帖子（后端计算）
// const farmerHotPosts = computed(() => {
//   const farmerPosts = props.posts.filter(post => post.author?.type === 'farmer')
//   return calculateHotPosts(farmerPosts).slice(0, 10)
// })

// const buyerHotPosts = computed(() => {
//   const buyerPosts = props.posts.filter(post => post.author?.type === 'buyer')
//   return calculateHotPosts(buyerPosts).slice(0, 10)
// })

// 计算帖子热度
const calculateHotPosts = (posts) => {
  return posts.map(post => {
    // 热度计算公式：点赞数 * 0.6 + 评论数 * 0.4 + 时间衰减因子
    const likes = post.likes || 0
    const commentsCount = post.comments?.length || 0
    
    // 时间衰减因子（帖子发布时间越近，热度越高）
    const createTime = new Date(post.createTime).getTime()
    const now = Date.now()
    const hoursDiff = (now - createTime) / (1000 * 60 * 60) // 小时差
    const timeFactor = Math.max(0, 1 - hoursDiff / 168) // 一周内有效，168小时
    
    // 计算热度分数
    const hotScore = (likes * 0.6 + commentsCount * 0.4) * (1 + timeFactor * 0.5)
    
    return {
      ...post,
      hotScore: Math.round(hotScore * 100) / 100 // 保留两位小数
    }
  }).sort((a, b) => b.hotScore - a.hotScore) // 按热度降序排列
}

// 获取排名样式
const getRankClass = (index) => {
  if (index === 0) return 'rank-1'
  if (index === 1) return 'rank-2'
  if (index === 2) return 'rank-3'
  return 'rank-other'
}

// 查看帖子详情
const viewPostDetail = (post) => {
  selectedPost.value = post
  showPostDetail.value = true
}

// 刷新热门帖子
const refreshHotPosts = () => {
  loading.value = true
  ElMessage.success('热门帖子已刷新')
  
  // 模拟刷新延迟
  setTimeout(() => {
    loading.value = false
  }, 1000)
}

const handleLike = (postId) => {
  emit('like', postId)
}

// 处理点踩
const handleDislike = (postId) => {
  emit('dislike', postId)
}

// 处理添加评论
const handleAddComment = (commentData) => {
  emit('add-comment', commentData)
}

// 处理添加回复
const handleAddReply = (replyData) => {
  emit('add-reply', replyData)
}

onMounted(() => {
  // 组件挂载时的初始化逻辑
})

//测试用例
const samplePosts = [
  {
    id: 1,
    content: "今年的苹果大丰收啦！红富士又大又甜，欢迎各地商家前来采购，价格优惠，量大从优！",
    keywords: ["苹果", "丰收", "采购"],
    images: [],
    type: "farmer",
    privacy: "public",
    author: {
      id: 101,  // 确保有 id 字段
      name: "张大叔果园",
      avatar: "https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=100&h=100&fit=crop",
      type: "farmer"
    },
    createTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
    likes: 42,
    dislikes: 1,
    comments: [
      { 
        id: 1, 
        content: "价格怎么样？", 
        author: { 
          id: 201,  // 评论作者也要有 id
          name: "采购商李总" 
        }, 
        createTime: new Date().toISOString() 
      },
      { 
        id: 2, 
        content: "有包装好的吗？", 
        author: { 
          id: 202,
          name: "水果批发王老板" 
        }, 
        createTime: new Date().toISOString() 
      }
    ],
    userAction: null,
    showComments: false
  },
]
</script>

<style scoped>
.hot-posts {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.hot-posts-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.hot-posts-header h2 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
}

.hot-posts-content {
  padding: 0;
}

.hot-section {
  padding: 20px 24px;
  border-bottom: 1px solid #f3f4f6;
}

.hot-section:last-child {
  border-bottom: none;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e5e7eb;
}

.section-tag {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 600;
}

.section-count {
  font-size: 0.875rem;
  color: #6b7280;
  font-weight: 500;
}

.hot-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.hot-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.hot-item:hover {
  background: #f8fafc;
  border-color: #e5e7eb;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.hot-item.top-three {
  background: linear-gradient(135deg, #fff9e6, #fff3e0);
  border: 1px solid #ffd54f;
}

.hot-rank {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
}

.rank-number {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  font-size: 0.875rem;
  font-weight: 600;
  color: white;
}

.rank-1 {
  background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
  box-shadow: 0 2px 4px rgba(255, 107, 107, 0.3);
}

.rank-2 {
  background: linear-gradient(135deg, #4ecdc4, #88d3ce);
  box-shadow: 0 2px 4px rgba(78, 205, 196, 0.3);
}

.rank-3 {
  background: linear-gradient(135deg, #45b7d1, #7bcde3);
  box-shadow: 0 2px 4px rgba(69, 183, 209, 0.3);
}

.rank-other {
  background: #9ca3af;
  color: white;
}

.hot-content {
  flex: 1;
  min-width: 0;
}

.post-text {
  margin: 0 0 8px 0;
  color: #374151;
  font-size: 0.875rem;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  word-break: break-word;
}

.post-stats {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 0.75rem;
  color: #6b7280;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.hot-score {
  margin-left: auto;
  font-weight: 600;
  color: #f59e0b;
  background: #fef3c7;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 0.7rem;
}

.empty-state {
  padding: 40px 20px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .hot-posts-header {
    padding: 16px 20px;
  }
  
  .hot-section {
    padding: 16px 20px;
  }
  
  .hot-item {
    padding: 12px;
  }
  
  .post-stats {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .hot-score {
    margin-left: 0;
  }
}

@media (max-width: 480px) {
  .hot-posts-header h2 {
    font-size: 1.25rem;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .hot-item {
    flex-direction: column;
    gap: 8px;
  }
  
  .hot-rank {
    align-self: flex-start;
  }
}
</style>